package org.luckyjourney.mq.customer;

import lombok.extern.slf4j.Slf4j;
import org.luckyjourney.entity.AggregatedUpdate;
import org.luckyjourney.entity.vo.Model;
import org.luckyjourney.entity.vo.UserModel;
import org.luckyjourney.service.user.UserService;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @creator: liRong
 * @date: 2025/6/26 15:19
 */
@Slf4j
@Component
public class ModelUpdateConsumer {

    @Autowired
    private UserService userService;

    @RabbitListener(queues = "model.aggregation.queue")
    public void handleAggregatedUpdates(Map<Long , List<AggregatedUpdate>> groupUpdates) {
        if(!groupUpdates.isEmpty()) {
            // 记录处理开始时间
            long startTime = System.currentTimeMillis();
            int userCount = groupUpdates.size();
            int updateCount = 0;

            try {
                // 每一个用户 的 每一个修改的标签概率
                for (Map.Entry<Long, List<AggregatedUpdate>> entry : groupUpdates.entrySet()) {
                    UserModel userModel = new UserModel();

                    // 安全转换 String 到 Long
                    Long userId;
                    try {
                        userId = Long.parseLong(String.valueOf(entry.getKey()));
                    } catch (NumberFormatException e) {
                        log.error("无效的用户ID格式: {}", entry.getKey());
                        continue;
                    }

                    userModel.setUserId(userId);
                    System.out.println(userId);
                    // 遍历 该用户的所有标签修改
                    List<Model> models = new ArrayList<>();
                    for (AggregatedUpdate aggregatedUpdate : entry.getValue()) {
                        Model model = new Model();
                        model.setLabel(aggregatedUpdate.getLabel());
                        model.setVideoId(aggregatedUpdate.getVideoId());
                        model.setScore(aggregatedUpdate.getTotalScore());

                        models.add(model);
                        updateCount++;
                    }
                    userModel.setModels(models);

                    userService.updateUserModel(userModel);
                }
                // 记录处理耗时
                long duration = System.currentTimeMillis() - startTime;
                log.info("处理完成: {}个用户的{}个更新, 耗时{}ms", userCount, updateCount, duration);

            } catch (Exception e) {
                log.error("处理聚合更新失败", e);
                // 这里可以添加重试或错误处理逻辑
                throw new AmqpRejectAndDontRequeueException(e);
            }
        }
    }

}
